package com.example.myapplication;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

public class CustomListActivity extends AppCompatActivity {
    private ListView mylist2;
    private ProgressBar progressBar;
    private CurrencyAdapter adapter;
    private final List<HashMap<String, String>> listItems = new ArrayList<>();
    private final Handler handler = new Handler(Looper.getMainLooper());

    // 数据库相关
    private DBManager dbManager;
    private static final String DATE_SP_KEY = "rate_date";
    private SharedPreferences sp;
    private String logDate;

    // Intent键值
    private static final String CURRENCY_NAME = "CURRENCY_NAME";
    private static final String EXCHANGE_RATE = "EXCHANGE_RATE";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_list);

        // 初始化数据库和SharedPreferences
        dbManager = new DBManager(this);
        sp = getSharedPreferences("rate_prefs", MODE_PRIVATE);
        logDate = sp.getString(DATE_SP_KEY, "");

        initViews();
        setupAdapter();
        setupClickListener();
        startDataLoading();

    }



    private void initViews() {
        mylist2 = findViewById(R.id.mylist2);
        progressBar = findViewById(R.id.progressBar);
    }

    private void setupAdapter() {
        adapter = new CurrencyAdapter(this, listItems);
        mylist2.setAdapter(adapter);
    }

    private void setupClickListener() {
        mylist2.setOnItemClickListener((parent, view, position, id) -> {
            HashMap<String, String> item = adapter.getItem(position);
            handleCurrencyClick(item);
        });
    }

    private void handleCurrencyClick(HashMap<String, String> item) {
        try {
            String currency = item.get("currency");
            double rate = Double.parseDouble(item.get("rate").replaceAll("[^\\d.]", ""));

            Intent intent = new Intent(this, CalculateActivity.class);
            intent.putExtra(CURRENCY_NAME, currency);
            intent.putExtra(EXCHANGE_RATE, rate);
            startActivity(intent);

        } catch (NumberFormatException e) {
            Toast.makeText(this, "汇率格式错误", Toast.LENGTH_SHORT).show();
            Log.e("PARSE_ERROR", "无效的汇率数据: " + e.getMessage());
        }
    }

    private void startDataLoading() {
        new Thread(dataFetchRunnable).start();
        handler.post(() -> {
            progressBar.setVisibility(View.VISIBLE);
            mylist2.setVisibility(View.GONE);
        });
    }

    private final Runnable dataFetchRunnable = new Runnable() {
        @Override
        public void run() {
            String currentDate = new SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(new Date());

            if (currentDate.equals(logDate)) {
                loadFromDatabase();
            } else {
                fetchFromNetwork(currentDate);
            }
        }

        private void loadFromDatabase() {
            List<RateItem> localData = dbManager.listAll();
            if (!localData.isEmpty()) {
                updateUIWithLocalData(localData);
            } else {
                handler.post(() -> {
                    Toast.makeText(CustomListActivity.this,
                            "本地无数据，尝试网络获取", Toast.LENGTH_SHORT).show();
                    fetchFromNetwork(getCurrentDate());
                });
            }
        }

        private void fetchFromNetwork(String currentDate) {
            try {
                Document doc = Jsoup.connect("https://www.huilvbiao.com/bank/spdb").get();
                List<RateItem> newData = parseHtmlData(doc);

                if (!newData.isEmpty()) {
                    // 保存到数据库并更新日期
                    dbManager.addAll(newData);
                    sp.edit().putString(DATE_SP_KEY, currentDate).apply();
                    updateUIWithLocalData(newData);
                } else {
                    handler.post(() -> Toast.makeText(CustomListActivity.this,
                            "获取到空数据", Toast.LENGTH_SHORT).show());
                }

            } catch (Exception e) {
                handleNetworkError(e);
                Log.e("NETWORK_ERROR", "网络请求失败: " + e.getMessage());
            }
        }

        private List<RateItem> parseHtmlData(Document doc) {
            List<RateItem> items = new ArrayList<>();
            Element table = doc.selectFirst("table.table-bordered");

            if (table != null) {
                for (Element row : table.select("tbody tr")) {
                    Element currencyElem = row.selectFirst("th a.coin span");
                    Element rateElem = row.selectFirst("td");

                    if (currencyElem != null && rateElem != null) {
                        try {
                            String currency = currencyElem.text().trim();
                            double rate = parseRate(rateElem.text().trim());
                            items.add(new RateItem(currency, rate));
                        } catch (NumberFormatException e) {
                            Log.e("PARSE_ERROR", "无效汇率格式: " + rateElem.text());
                        }
                    }
                }
            }
            return items;
        }

        private double parseRate(String rateStr) throws NumberFormatException {
            return Double.parseDouble(rateStr.replaceAll("[^\\d.]", ""));
        }

        private void handleNetworkError(Exception e) {
            List<RateItem> localData = dbManager.listAll();
            handler.post(() -> {
                if (localData.isEmpty()) {
                    Toast.makeText(CustomListActivity.this,
                            "网络连接失败且无本地数据", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(CustomListActivity.this,
                            "使用本地缓存数据", Toast.LENGTH_SHORT).show();
                    updateUIWithLocalData(localData);
                }
            });
        }

        private String getCurrentDate() {
            return new SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(new Date());
        }
    };

    private void updateUIWithLocalData(List<RateItem> data) {
        handler.post(() -> {
            progressBar.setVisibility(View.GONE);
            mylist2.setVisibility(View.VISIBLE);

            listItems.clear();
            for (RateItem item : data) {
                HashMap<String, String> map = new HashMap<>();
                map.put("currency", item.getCurrencyName());
                map.put("rate", String.valueOf(item.getRateValue()));
                listItems.add(map);
            }
            adapter.notifyDataSetChanged();
            Log.i("DATA_LOAD", "加载数据量: " + listItems.size());
        });
    }
}